Which order to define getters and setters in? [closed]

Posted by N.N. on Programmers See other posts from Programmers or by N.N.
Published on 2012-10-09T13:04:50Z Indexed on 2012/10/09 21:58 UTC
Read the original article Hit count: 133

Is there a best practice for the order to define getters and setters in? There seems to be two practices:

  • getter/setter pairs
  • first getters, then setters (or the other way around)

To illuminate the difference here is a Java example of getter/setter pairs:

public class Foo {
    private int var1,
    var2,
    var3;

    public int getVar1() {
    return var1;
    }

    public void setVar1(int var1) {
    this.var1 = var1;
    }

    public int getVar2() {
    return var2;
    }

    public void setVar2(int var2) {
    this.var2 = var2;
    }

    public int getVar3() {
    return var3;
    }

    public void setVar3(int var3) {
    this.var3 = var3;
    }
}

And here is a Java example of first getters, then setters:

public class Foo {
    private int var1,
    var2,
    var3;

    public int getVar1() {
    return var1;
    }

    public int getVar2() {
    return var2;
    }

    public int getVar3() {
    return var3;
    }

    public void setVar1(int var1) {
    this.var1 = var1;
    }

    public void setVar2(int var2) {
    this.var2 = var2;
    }

    public void setVar3(int var3) {
    this.var3 = var3;
    }
}

I think the latter type of ordering is clearer both in code and in class diagrams but I do not know if that is enough to rule out the other type of ordering.

© Programmers or respective owner

Related posts about object-oriented

Related posts about patterns-and-practices